package com.material.common.wx.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author ganxinge
 */
public class WeChatUtil {
    static Charset CHARSET = Charset.forName("utf-8");

    /**
     * 开发者设置的token，微信小店消息推送的token令牌
     */
    private static final String TOKEN = "pamtest";
    /**
     * 微信小店设置开发者设置的EncodingAESKey，消息密钥
     */
    private static final String ENCODING_AES_KEY = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG";
    /**
     * 微信小店的appId wx5bd97b1385d6e8f6
     */
    private static final String APP_ID = "wxb11529c136998cb6";




    public static void main(String[] args) throws Exception {
        String replyMsg = "{\"ToUserName\":\"oia2TjjewbmiOUlr6X-1crbLOvLw\",\"FromUserName\":\"gh_7f083739789a\",\"CreateTime\":1662480000,\"MsgType\":\"event\",\"Event\":\"channels_ec_order_pay\",\"order_info\":{\"order_id\":3705115058471208928,\"pay_time\":1658509200}}";
        String timeStamp = "1409304348";
        String nonce = "xxxxxx";
        //模拟构建微信传过来的加密消息内容
        String encryptMsgBody = buildEncryptMsgBody(replyMsg, timeStamp, nonce, APP_ID, ENCODING_AES_KEY);
        System.out.println("加密的消息体："+encryptMsgBody);
        JSONObject jsonObject = JSON.parseObject(encryptMsgBody);
        String msgSignature = jsonObject.getString("MsgSignature");
        //得到加密的数据
        String encrypt = jsonObject.getString("Encrypt");
        boolean verify = verifySignature(msgSignature, timeStamp, nonce, encrypt);
        if(verify){
            String decryptMessage = decryptMessage(encrypt, ENCODING_AES_KEY,APP_ID);
            System.out.println("解密的消息："+decryptMessage);
        }else {
            System.out.println("消息签名验证失败");
        }
    }

    /**
     * 构建加密的消息体
     * @param replyMsg：{"ToUserName":"oia2TjjewbmiOUlr6X-1crbLOvLw","FromUserName":"gh_7f083739789a","CreateTime":1662480000,"MsgType":"event","Event":"channels_ec_order_pay","order_info":{"order_id":3705115058471208928,"pay_time":1658509200}}
     * @param timeStamp： 1409304348
     * @param nonce： xxxxxx
     * @param appId： wxb11529c136998cb6
     * @return
     */
    public static String buildEncryptMsgBody(String replyMsg, String timeStamp, String nonce,String appId,String encodingAesKey)  {
        if (encodingAesKey.length() != 43) {
            throw new RuntimeException("AES KEY 长度不正确");
        }
        // 加密
        String encrypt = encrypt(getRandomStr(), replyMsg,appId,encodingAesKey);
        // 生成安全签名
        if (timeStamp == "") {
            timeStamp = Long.toString(System.currentTimeMillis());
        }
        String signature = getSHA1(TOKEN, timeStamp, nonce, encrypt);

        Map<String,String> params = new HashMap<>();
        params.put("Encrypt",encrypt);
        params.put("ToUserName","gh_7f083739789a");
        params.put("MsgSignature",signature);
        //params.put("TimeStamp",timeStamp);
        //params.put("Nonce",nonce);
        String result = JSON.toJSONString(params);
        return result;
    }

    /**
     * 获取随机数
     * @return
     */
    private static String getRandomStr() {
        String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 16; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 对消息内容进行加密
     * @param randomStr
     * @param text
     * @param appId
     * @return
     */
    private static String encrypt(String randomStr, String text,String appId,String encodingAesKey) {
        ByteGroup byteCollector = new ByteGroup();
        byte[] randomStrBytes = randomStr.getBytes(CHARSET);
        byte[] textBytes = text.getBytes(CHARSET);
        byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length);
        byte[] appidBytes = appId.getBytes(CHARSET);

        // randomStr + networkBytesOrder + text + appid
        byteCollector.addBytes(randomStrBytes);
        byteCollector.addBytes(networkBytesOrder);
        byteCollector.addBytes(textBytes);
        byteCollector.addBytes(appidBytes);

        // ... + pad: 使用自定义的填充方式对明文进行补位填充
        byte[] padBytes = PKCS7Encoder.encode(byteCollector.size());
        byteCollector.addBytes(padBytes);

        // 获得最终的字节流, 未加密
        byte[] unencrypted = byteCollector.toBytes();
        try {
            byte[] aesKey = Base64.getDecoder().decode(encodingAesKey + "=");
            // 设置加密模式为AES的CBC模式
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
            IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);

            // 加密
            byte[] encrypted = cipher.doFinal(unencrypted);
            // 使用BASE64对加密后的字符串进行编码
            Base64.Encoder encoder = Base64.getEncoder();
            String base64Encrypted = encoder.encodeToString(encrypted);

            return base64Encrypted;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("-40006");
        }
    }

    /**
     * 生成4个字节的网络字节序
     * @param sourceNumber
     * @return
     */
    private static byte[] getNetworkBytesOrder(int sourceNumber) {
        byte[] orderBytes = new byte[4];
        orderBytes[3] = (byte) (sourceNumber & 0xFF);
        orderBytes[2] = (byte) (sourceNumber >> 8 & 0xFF);
        orderBytes[1] = (byte) (sourceNumber >> 16 & 0xFF);
        orderBytes[0] = (byte) (sourceNumber >> 24 & 0xFF);
        return orderBytes;
    }


    /**
     * 发起验证
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */
    private static boolean verifySignature(String signature, String timestamp, String nonce) {
        // 将 Token、timestamp 和 nonce 放入数组
        String[] params = {TOKEN, timestamp, nonce};
        // 对数组进行字典序排序
        Arrays.sort(params);

        // 拼接成一个字符串
        StringBuilder sb = new StringBuilder();
        for (String param : params) {
            sb.append(param);
        }
        String temp = sb.toString();

        // 进行 SHA-1 哈希计算
        String sha1 = sha1(temp);

        // 比较计算结果与请求中的 signature
        return sha1.equals(signature);
    }

    /**
     * 验证消息的signature
     * @param msgSignature
     * @param timestamp
     * @param nonce
     * @param encrypt
     * @return
     */
    public static boolean verifySignature(String msgSignature, String timestamp, String nonce, String encrypt) {
        // 将 token、timestamp、nonce、encrypt 四个参数进行字典序排序
        String[] params = {TOKEN, timestamp, nonce, encrypt};
        Arrays.sort(params);

        // 拼接成一个字符串
        StringBuilder sb = new StringBuilder();
        for (String param : params) {
            sb.append(param);
        }
        String temp = sb.toString();

        // 进行 SHA-1 哈希计算
        String sha1 = sha1(temp);
        System.out.println("server sign:"+sha1);
        System.out.println("client sign:"+msgSignature);
        return sha1.equals(msgSignature);
    }

    /**
     * 解密消息内容
     * @param encrypt
     * @return
     * @throws Exception
     */
    public static String decryptMessage(String encrypt,String encodeAesKey,String appId) throws Exception {
        // AESKey = Base64_Decode( EncodingAESKey + "=" )
        if (encodeAesKey.length() != 43) {
            throw new RuntimeException("AES KEY 长度不正确");
        }
        byte[] aesKey = Base64.getDecoder().decode(encodeAesKey + "=");

        // 将 Encrypt 密文进行 Base64 解码
        byte[] encryptedBytes = Base64.getDecoder().decode(encrypt);

        // 使用 AESKey 进行 AES 解密
        SecretKeySpec secretKeySpec = new SecretKeySpec(aesKey, "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(aesKey, 0, 16);
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);

        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

        // 去除补位字符
        byte[] bytes = PKCS7Encoder.decode(decryptedBytes);

        // 分离16位随机字符串,网络字节序和AppId
        byte[] networkOrder = Arrays.copyOfRange(bytes, 16, 20);

        int xmlLength = recoverNetworkBytesOrder(networkOrder);

        String content = new String(Arrays.copyOfRange(bytes, 20, 20 + xmlLength), CHARSET);
        String fromAppId = new String(Arrays.copyOfRange(bytes, 20 + xmlLength, bytes.length),
                CHARSET);

        // 验证 appid
        if (!fromAppId.equals(appId)) {
            throw new RuntimeException("appId does not match");
        }

        // 返回解密后的消息
        return content;
    }

    // 还原4个字节的网络字节序
    private static int recoverNetworkBytesOrder(byte[] orderBytes) {
        int sourceNumber = 0;
        for (int i = 0; i < 4; i++) {
            sourceNumber <<= 8;
            sourceNumber |= orderBytes[i] & 0xff;
        }
        return sourceNumber;
    }

    private static String getSHA1(String token, String timestamp, String nonce, String encrypt) {
        try {
            String[] array = new String[] { token, timestamp, nonce, encrypt };
            StringBuffer sb = new StringBuffer();
            // 字符串排序
            Arrays.sort(array);
            for (int i = 0; i < 4; i++) {
                sb.append(array[i]);
            }
            String str = sb.toString();
            // SHA1签名生成
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(str.getBytes());
            byte[] digest = md.digest();

            StringBuffer hexstr = new StringBuffer();
            String shaHex = "";
            for (int i = 0; i < digest.length; i++) {
                shaHex = Integer.toHexString(digest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexstr.append(0);
                }
                hexstr.append(shaHex);
            }
            return hexstr.toString();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("40003");
        }
    }

    private static String sha1(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            byte[] bytes = md.digest(input.getBytes("UTF-8"));
            StringBuilder sb = new StringBuilder();
            for (byte b : bytes) {
                String hex = Integer.toHexString((b & 0xff) | 0x100).substring(1, 3);
                sb.append(hex);
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException | java.io.UnsupportedEncodingException e) {
            throw new RuntimeException("SHA-1 algorithm not found", e);
        }
    }


}
